/*
 * @Author: zzh
 * @Date: 2021-05-27 10:31:11
 * @LastEditTime: 2021-05-27 10:41:39
 * @LastEditors: Please set LastEditors
 * @Description: 全局处理错误方法
 * @FilePath: \egg-demo\app\middleware\errorHandle.js
 */
'use strict';

module.exports = (option, app) => {
  return async function(ctx, next) {
    try {
      await next();
    } catch(err) {
      // 将所有的异常都在app上触发一个error事件， 框架会记录一条错误日志；
      app.emit('error', err, this)
      const status = err.status || 500;
      const error = status === 500 && app.config.env === 'prod' ? 'Internal Server Error...' : err.message;
      ctx.body = { error }
      if( status === 422 ) {
        ctx.body.detail = err.errors;
      }
      ctx.status = status;
    }
  }
};